﻿namespace com.game.module.Arena
{
    using com.game;
    using com.game.basic;
    using com.game.basic.events;
    using com.game.data;
    using com.game.Interface.Tick;
    using com.game.manager;
    using com.game.module.core;
    using com.game.module.WiFiPvP;
    using com.game.utils;
    using com.game.vo;
    using com.u3d.bases.ai;
    using com.u3d.bases.display;
    using com.u3d.bases.display.character;
    using PCustomDataType;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.CompilerServices;
    using UnityEngine;

    public class ArenaManager : ITick
    {
        private int _arenaBattleType = -1;
        private List<PCoordinator> _challengerCoorList = new List<PCoordinator>();
        private IList<KeyValuePair<Vector3, int>> _challengerPosList = new List<KeyValuePair<Vector3, int>>();
        private IList<KeyValuePair<Vector3, int>> _defenderPosList = new List<KeyValuePair<Vector3, int>>();
        private readonly IDictionary<ActionDisplay, FightCounter> _enemyDic = new Dictionary<ActionDisplay, FightCounter>();
        private bool _isConfirming;
        private bool _isInitialized;
        private readonly IDictionary<ActionDisplay, FightCounter> _playerDic = new Dictionary<ActionDisplay, FightCounter>();
        private ArenaConst.ArenaStatus _status = ArenaConst.ArenaStatus.ended;
        [CompilerGenerated]
        private static Func<PlayerDisplay, bool> <>f__am$cache14;
        [CompilerGenerated]
        private static Func<PGeneralSkillInfo, uint> <>f__am$cache15;
        public IList<PGeneralFightAttr> EnemyAttrList = new List<PGeneralFightAttr>();
        public static readonly ArenaManager Instance;
        public IList<PGeneralFightAttr> MyAttrList = new List<PGeneralFightAttr>();
        public SysArenaVo Template;

        static ArenaManager()
        {
            if (Instance == null)
            {
            }
            Instance = new ArenaManager();
        }

        private ArenaManager()
        {
            GlobalAPI.tickManager.addTick(this);
            GlobalAPI.facade.Add(15, new NoticeListener(this.InitPlayersToMap));
            GlobalAPI.facade.Add(0x10, new NoticeListener(this.ShowCountingDown));
            GlobalAPI.facade.Add(0x10, new NoticeListener(this.CheckShouldOpenArenaView));
            GlobalAPI.facade.Add(200, new NoticeListener(this.ArenaReadyToFight));
        }

        private bool AliveSelector(KeyValuePair<ActionDisplay, FightCounter> kv)
        {
            return !kv.Key.GetMeVoByType<BaseRoleVo>().IsEmptyHp;
        }

        private void ArenaReadyToFight(int type, int v1, int v2, object data)
        {
            if (AppMap.Instance.IsInArena)
            {
                this._playerDic.Clear();
                this._enemyDic.Clear();
                foreach (PlayerDisplay display in AppMap.Instance.SelfplayerList)
                {
                    this._playerDic.Add(display, new FightCounter());
                    display.Controller.AiController.SetAi(true);
                }
                if (<>f__am$cache14 == null)
                {
                    <>f__am$cache14 = x => x.GetVo().Camp != 0;
                }
                IEnumerator<PlayerDisplay> enumerator2 = AppMap.Instance.playerList.Where<PlayerDisplay>(<>f__am$cache14).GetEnumerator();
                try
                {
                    while (enumerator2.MoveNext())
                    {
                        PlayerDisplay key = enumerator2.Current;
                        this._enemyDic.Add(key, new FightCounter());
                    }
                }
                finally
                {
                    if (enumerator2 == null)
                    {
                    }
                    enumerator2.Dispose();
                }
                vp_Timer.In(2f, delegate {
                    IEnumerator<ActionDisplay> enumerator = this._enemyDic.Keys.GetEnumerator();
                    try
                    {
                        while (enumerator.MoveNext())
                        {
                            ActionDisplay current = enumerator.Current;
                            current.Controller.AiController.SetAi(true);
                        }
                    }
                    finally
                    {
                        if (enumerator == null)
                        {
                        }
                        enumerator.Dispose();
                    }
                }, null);
                this.Status = ArenaConst.ArenaStatus.started;
            }
        }

        public void CheckShouldOpenArenaView(int type, int v1, int v2, object data)
        {
            if (Instance.Status == ArenaConst.ArenaStatus.ending)
            {
                Singleton<ArenaView>.Instance.OpenView();
                Instance.Status = ArenaConst.ArenaStatus.ended;
            }
        }

        public void Clear()
        {
            this._isInitialized = false;
            this._isConfirming = false;
            this.Template = null;
            this.MyAttrList.Clear();
            this.EnemyAttrList.Clear();
            Singleton<ArenaMode>.Instance.LastChallenger = null;
            int num = 0;
            this.EnemyTotalKill = num;
            this.TotalKill = num;
            float num2 = 0f;
            this.ActualTime = num2;
            this.TotalTime = num2;
            this._enemyDic.Clear();
            this._playerDic.Clear();
            this.Status = ArenaConst.ArenaStatus.ending;
        }

        public void ConfirmEndStatus()
        {
            ArenaConst.ArenaStatus status = this.Status;
            if (status == ArenaConst.ArenaStatus.confirming_win)
            {
                this.Status = ArenaConst.ArenaStatus.win;
            }
            else if (status == ArenaConst.ArenaStatus.confirming_failed)
            {
                this.Status = ArenaConst.ArenaStatus.failed;
            }
            else
            {
                this.Status = ArenaConst.ArenaStatus.failed;
            }
        }

        public void DenyEndStatus()
        {
            this.Status = ArenaConst.ArenaStatus.failed;
        }

        private void DoParseIntToKV(int[] array, ref IList<KeyValuePair<Vector3, int>> targetList)
        {
            targetList.Clear();
            for (int i = 0; i < array.Count<int>(); i += 4)
            {
                int num2 = array[i];
                int num3 = array[i + 1];
                int num4 = array[i + 2];
                int num5 = array[i + 3];
                Vector3 key = new Vector3((float) num2, (float) num3, (float) num4);
                KeyValuePair<Vector3, int> item = new KeyValuePair<Vector3, int>(key, num5);
                targetList.Add(item);
            }
        }

        public void EnemyIncreaseDeadCount(ActionDisplay player)
        {
            if (this._enemyDic.ContainsKey(player))
            {
                this._enemyDic[player].AddDeadCount();
                this.EnemyTotalDead++;
            }
        }

        public void EnemyIncreaseKillCount(ActionDisplay player)
        {
            if (this._enemyDic.ContainsKey(player))
            {
                this._enemyDic[player].AddKillCount();
                this.EnemyTotalKill++;
            }
            else
            {
                Debug.LogWarning("非敌方杀人");
            }
        }

        public void Enter(IList<PGeneralFightAttr> mylist, IList<PGeneralFightAttr> enemyList)
        {
            this.MyAttrList = mylist;
            this.EnemyAttrList = enemyList;
            this.Template = BaseDataMgr.instance.GetArenaVo(1);
            this.HandleTemplate(this.Template);
            this._isInitialized = true;
        }

        ~ArenaManager()
        {
            GlobalAPI.tickManager.removeTick(this);
            GlobalAPI.facade.Remove(15, new NoticeListener(this.InitPlayersToMap));
            GlobalAPI.facade.Remove(0x10, new NoticeListener(this.ShowCountingDown));
            GlobalAPI.facade.Remove(0x10, new NoticeListener(this.CheckShouldOpenArenaView));
            GlobalAPI.facade.Remove(200, new NoticeListener(this.ArenaReadyToFight));
        }

        public void FixCoordinator(List<MeVo> playerList)
        {
            foreach (MeVo vo in playerList)
            {
                foreach (PCoordinator coordinator in this._challengerCoorList)
                {
                    if (vo.Id == coordinator.id)
                    {
                        vo.X = coordinator.x * 0.001f;
                        vo.Y = coordinator.y * 0.001f;
                        vo.Z = coordinator.z * 0.001f;
                        vo.rotateY = coordinator.rotateY;
                    }
                }
            }
            this._challengerCoorList.Clear();
        }

        private List<PCoordinator> GeneratePosForPlayers(IEnumerable<PGeneralFightAttr> attrList, bool isMySide)
        {
            int num = 3;
            int num2 = 0;
            List<PCoordinator> list = new List<PCoordinator>();
            IList<KeyValuePair<Vector3, int>> list2 = !isMySide ? this._defenderPosList : this._challengerPosList;
            IEnumerator<PGeneralFightAttr> enumerator = attrList.GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    KeyValuePair<Vector3, int> pair;
                    PGeneralFightAttr current = enumerator.Current;
                    int career = BaseDataMgr.instance.GetGeneralVo(current.attr.generalId, current.attr.quality).career;
                    ulong id = current.attr.id;
                    if (career == 2)
                    {
                        Debug.Log("前排");
                        pair = list2[num2];
                        num2++;
                    }
                    else
                    {
                        Debug.Log("后排");
                        pair = list2[num];
                        num++;
                    }
                    PCoordinator item = new PCoordinator {
                        type = 1,
                        id = id,
                        lv = 1,
                        x = (int) pair.Key.x,
                        y = (int) pair.Key.y,
                        z = (int) pair.Key.z,
                        rotateY = pair.Value
                    };
                    list.Add(item);
                }
            }
            finally
            {
                if (enumerator == null)
                {
                }
                enumerator.Dispose();
            }
            return list;
        }

        public List<uint> GetSkillIdListForEnemyInArena(ulong id)
        {
            <GetSkillIdListForEnemyInArena>c__AnonStoreyD4 yd = new <GetSkillIdListForEnemyInArena>c__AnonStoreyD4 {
                id = id
            };
            List<uint> list = new List<uint>();
            PGeneralFightAttr attr = this.EnemyAttrList.FirstOrDefault<PGeneralFightAttr>(new Func<PGeneralFightAttr, bool>(yd.<>m__4E));
            if (attr != null)
            {
                if (<>f__am$cache15 == null)
                {
                    <>f__am$cache15 = skill => (skill.groupId * 0x3e8) + skill.skillLvl;
                }
                list.AddRange(attr.skill.Select<PGeneralSkillInfo, uint>(<>f__am$cache15));
            }
            return list;
        }

        public FightCounter GetStaticsByTid(ulong id, bool isMe)
        {
            <GetStaticsByTid>c__AnonStoreyD3 yd = new <GetStaticsByTid>c__AnonStoreyD3 {
                id = id
            };
            IDictionary<ActionDisplay, FightCounter> dictionary = !isMe ? this._enemyDic : this._playerDic;
            ActionDisplay display = dictionary.Keys.FirstOrDefault<ActionDisplay>(new Func<ActionDisplay, bool>(yd.<>m__4B));
            return ((display == null) ? null : dictionary[display]);
        }

        private void HandleTemplate(SysArenaVo template)
        {
            if (template == null)
            {
                Debug.LogError("竞技场模板表为空");
            }
            else
            {
                int[] arrayStringToInt = StringUtils.GetArrayStringToInt(template.challenger_pos);
                int[] array = StringUtils.GetArrayStringToInt(template.defender_pos);
                this.DoParseIntToKV(arrayStringToInt, ref this._challengerPosList);
                this.DoParseIntToKV(array, ref this._defenderPosList);
                this.TotalTime = template.total_time;
                this.ActualTime = 0f;
                this.CountDown = template.counting_down;
                this._arenaBattleType = template.battle_mode;
            }
        }

        public void HandleWhenArenaEnd()
        {
            if (!this._isConfirming)
            {
                AiManagerBase.StopAllAi();
                Singleton<ArenaControl>.Instance.ArenaEnd();
                this._isConfirming = true;
            }
        }

        public void IncreaseDeadCount(ActionDisplay player)
        {
            if (this._playerDic.ContainsKey(player))
            {
                this._playerDic[player].AddDeadCount();
                this.TotalDead++;
            }
        }

        public void IncreaseKillCount(ActionDisplay player)
        {
            if (this._playerDic.ContainsKey(player))
            {
                this._playerDic[player].AddKillCount();
                this.TotalKill++;
            }
            else
            {
                Debug.LogWarning("非我方英雄杀人");
            }
        }

        public void InitPlayersToMap(int type, int v1, int v2, object data)
        {
            if (AppMap.Instance.IsInArena)
            {
                this._challengerCoorList = this.GeneratePosForPlayers(this.MyAttrList, true);
                Singleton<GeneralMode>.Instance.UpdateFightGeneralsAttrWhenArena(this.MyAttrList);
                List<PCoordinator> coorList = this.GeneratePosForPlayers(this.EnemyAttrList, false);
                Singleton<MapMode>.Instance.AddPlayerInCurrentArenaMap(this.EnemyAttrList, coorList, false);
                this.Status = ArenaConst.ArenaStatus.ready;
            }
        }

        private void ShowCountingDown(int type, int v1, int v2, object data)
        {
            if (AppMap.Instance.IsInArena && (this.Status == ArenaConst.ArenaStatus.ready))
            {
                Singleton<ArenaReadyMaskView>.Instance.OpenView();
            }
        }

        public void Update(int times, float dt)
        {
            Singleton<ArenaMode>.Instance.Update(times, dt);
            if ((this._isInitialized && !this._isConfirming) && (this.Status == ArenaConst.ArenaStatus.started))
            {
                this.TotalTime -= dt;
                this.ActualTime += RealTime.deltaTime;
                if (this.TotalTime <= 0f)
                {
                    if (this._enemyDic.Count<KeyValuePair<ActionDisplay, FightCounter>>(new Func<KeyValuePair<ActionDisplay, FightCounter>, bool>(this.AliveSelector)) > 0)
                    {
                        this.Status = ArenaConst.ArenaStatus.confirming_failed;
                    }
                }
                else if (this._playerDic.Count<KeyValuePair<ActionDisplay, FightCounter>>(new Func<KeyValuePair<ActionDisplay, FightCounter>, bool>(this.AliveSelector)) == 0)
                {
                    this.Status = ArenaConst.ArenaStatus.confirming_failed;
                }
                else if (this._enemyDic.Count<KeyValuePair<ActionDisplay, FightCounter>>(new Func<KeyValuePair<ActionDisplay, FightCounter>, bool>(this.AliveSelector)) == 0)
                {
                    this.Status = ArenaConst.ArenaStatus.confirming_win;
                }
            }
        }

        public float ActualTime { get; private set; }

        public float CountDown { get; private set; }

        public int EnemyTotalDead { get; private set; }

        public int EnemyTotalKill { get; private set; }

        public bool IsNeedHideBattleView
        {
            get
            {
                return (this._arenaBattleType == 0);
            }
        }

        public ArenaConst.ArenaStatus Status
        {
            get
            {
                return this._status;
            }
            set
            {
                if (this._status != value)
                {
                    this._status = value;
                    if ((value == ArenaConst.ArenaStatus.confirming_win) || (value == ArenaConst.ArenaStatus.confirming_failed))
                    {
                        this.HandleWhenArenaEnd();
                    }
                }
            }
        }

        public int TotalDead { get; private set; }

        public int TotalKill { get; private set; }

        public float TotalTime { get; private set; }

        [CompilerGenerated]
        private sealed class <GetSkillIdListForEnemyInArena>c__AnonStoreyD4
        {
            internal ulong id;

            internal bool <>m__4E(PGeneralFightAttr x)
            {
                return (x.attr.id == this.id);
            }
        }

        [CompilerGenerated]
        private sealed class <GetStaticsByTid>c__AnonStoreyD3
        {
            internal ulong id;

            internal bool <>m__4B(ActionDisplay x)
            {
                return (x.GetVo().Id == this.id);
            }
        }
    }
}

